<?php

/**
 * Description of Core_Config
 * @package Core
 * @author superx
 */
class Core_Config {

    protected static $_config;

    public static function init() {
        if (is_null(self::$_config)) {
            $global = include PROJECT_PATH . 'Config' . DIRECTORY_SEPARATOR . 'config.global.php';
            $env = include PROJECT_PATH . 'Config' . DIRECTORY_SEPARATOR . 'config.' . ENV . '.php';
            self::$_config = array_replace_recursive($global, $env);

            if (PHP_SAPI == 'cli') {
                $cli = include PROJECT_PATH . 'Config' . DIRECTORY_SEPARATOR . 'config.cli.php';
                self::$_config = array_replace_recursive(self::$_config, $cli);
            }
        }
    }

    /**
     * @param string $keystr
     * @param mixed $default
     * @return mixed
     */
    public static function get($keystr = '', $default = null) {
        $node = & self::$_config;
        if ($keystr) {
            $keys = explode('.', $keystr);
            foreach ($keys as $key) {
                if (isset($node[$key])) {
                    $node = & $node[$key];
                } else {
                    return $default;
                }
            }
        }
        return $node;
    }

    public static function set($keystr = '', $value = null) {
        $node = & self::$_config;
        if ($keystr) {
            $keys = explode('.', $keystr);
            foreach ($keys as $key) {
                if (!isset($node[$key])) {
                    $node[$key] = null;
                }
                $node = & $node[$key];
            }
            $node = $value;
        }
    }
}
